//! 客户端
use futures_util::{stream::SplitSink, SinkExt, StreamExt};
use log::*;
use spin::Mutex;
use spin::Once;
use std::sync::Arc;
use unmp::net;
use unmp_link::{Driver, ErrorKind, Link, ResultFuture};
use ws_stream_wasm::*;

static LINK: Once<Link> = Once::new();

struct ClientDriver {
    identifier: String,
    socket: Mutex<SplitSink<WsStream, WsMessage>>,
}
impl Driver for ClientDriver {
    fn name(&self) -> &str {
        &self.identifier
    }
    fn send(self: Arc<Self>, buf: &[u8]) -> ResultFuture {
        trace!("websocket_client send: {:02X?}.", buf);
        let (result_future, sender) = ResultFuture::new();
        let msg = WsMessage::Binary(Vec::from(buf));
        task_stream::spawn(async move {
            let mut ws = self.socket.lock();
            match ws.send(msg).await {
                Ok(_) => {
                    let _err = sender.send(Ok(()));
                }
                Err(_) => {
                    warn!("websocket_client send error.");
                    let _err = sender.send(Err(ErrorKind::TimedOut));
                }
            }
        });
        return result_future;
    }
}

/// 创建一个链路实例，并连接到指定地址端口
pub async fn start(url: &str) -> Result<Link, ()> {
    if let Some(_) = LINK.get() {
        return Err(());
    }
    let identifier = format!("{}", url);
    if let Some(_) = LINK.get() {
        return Err(());
    }

    let (_ws, wsio) = WsMeta::connect(url, None)
        .await
        .expect("ws connect fail.");
    let (sender, mut recver) = wsio.split();

    let driver = Arc::new(ClientDriver {
        identifier: identifier.clone(),
        socket: Mutex::new(sender),
    });
    let link_driver = Arc::downgrade(&driver);
    let link = Link::new(link_driver);
    info!("websocket_client new {:?}.", link);
    LINK.call_once(|| link.clone());

    let link_tmp = link.clone();
    task_stream::spawn(async move {
        let link = link_tmp;
        let _driver = driver;
        while let Some(message) = recver.next().await {
            match message {
                WsMessage::Binary(buf) => {
                    trace!("websocket_client recv: {:02X?}.", buf);

                    // 接收数据帧
                    net::when_recv(&link, &buf);
                }
                _ => {}
            };
        }
        warn!("websocket_client {:?} recv error.", link);
        link.destroy();
        panic!("ws disconnect.")
    });
    return Ok(link);
}
